<?php
declare (strict_types=1);

namespace app\user\service\user\admin;

use app\common\service\BaseService;
use app\user\logic\user\admin\UserLoginRecord as UserLoginRecordLogic;
use eduline\admin\libs\pageform\FormItem;
use eduline\admin\libs\pagelist\ListItem;
use eduline\admin\page\PageList;
use think\facade\Request;

/**
 * 学员登录日志
 */
class UserLoginRecord extends BaseService
{

    /**
     * 日志列表
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-08-04
     *
     * @return   [type]                         [description]
     */
    public function index()
    {
        // 搜索功能
        $map = [
            'user'      => [],
            '__TABLE__' => [],
        ];
        Request::has('phone', 'get', true) && $map['user'][] = ['phone', 'like', '%' . Request::get('phone/s') . '%'];
        if (request()->is_platform) {
            Request::has('mhm_id', 'get', true) && $map['user'][] = ['mhm_id', '=', Request::get('mhm_id/d')];
        } else {
            $map['user'][] = ['mhm_id', '=', request()->mhm_id];
        }
        Request::has('device_type', 'get', true) && $map['__TABLE__'][] = ['__TABLE__.device', '=', Request::get('device_type/s')];
        if (Request::has('time', 'get', true)) {
            $time               = Request::get('time/a');
            $map['__TABLE__'][] = ['__TABLE__.create_time', 'between', [strtotime($time[0]), strtotime($time[1])]];
        }
        $data = app(UserLoginRecordLogic::class)->getList($map)->bindAttr('user', ['avatar_url', 'nick_name', 'phone'])->hidden(['user']);
        // 定义字段
        $keyList = [
            'user'        => ListItem::make('custom')->title('用户'),
            'create_time' => ListItem::make()->title('登录时间'),
            'device_text' => ListItem::make()->title('登录设备'),
            'ip'          => ListItem::make()->title('登录IP'),
        ];

        // 设备选项
        $device_type = app(UserLoginRecordLogic::class)->getDeviceTypeOptions();
        $searchKey   = [
            'mhm_id'      => FormItem::make('searchSchool')->title(false)->visible(request()->is_platform),
            'device_type' => FormItem::make('select')->title(false)->placeholder('登录设备')->options($device_type),
            'phone'       => FormItem::make('input')->title(false)->placeholder('手机号')->maxlength(30),
            'time'        => FormItem::make('date')
                ->title(false)
                ->dateType(FormItem::option('DateType', 'DATETIME_RANGE'))
                ->format('yyyy-MM-dd HH:mm')
                ->startPlaceholder('登录开始时间')
                ->endPlaceholder('登录结束时间')
                ->required(),
        ];

        // 设置表单
        $list = app(PageList::class);
        // 表单字段
        $list->pageKey = $keyList;
        // 自定义排序
        // $list->pageKeySort = ['update_time DESC', 'user_name'];
        $list->searchKey = $searchKey;
        $list->datas     = $data;

        return $list->send();
    }

}
